package com.yksj.healthtalk.ui.server;

import java.util.ArrayList;
import java.util.Collection;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshListView;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.yksj.healthtalk.adapter.SalonAdapter;
import com.yksj.healthtalk.adapter.SalonAdapter.onClickSalonAttentionListener;
import com.yksj.healthtalk.adapter.SalonAdapter.onClickSalonHeadListener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.entity.GroupInfoEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartControlClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.chatting.ChatActivity;
import com.yksj.healthtalk.ui.salon.SalonInformationActivity;
import com.yksj.healthtalk.ui.salon.SalonReadSelf;
import com.yksj.healthtalk.ui.salon.SalonSelectPaymentOptionActivity.OnBuyTicketHandlerListener;
import com.yksj.healthtalk.utils.CollectUtils;
import com.yksj.healthtalk.utils.SalonHttpUtil;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 服务沙龙
 * 
 * @author Administrator
 * 
 */
public class ServerCenterServerSalonActivity extends BaseFragmentActivity implements OnClickListener, OnRefreshListener<ListView>,
		onClickSalonHeadListener, onClickSalonAttentionListener,
		OnItemClickListener, OnBuyTicketHandlerListener {

	private PullToRefreshListView mPullToRefreshListView;
	private ListView mListView;
	private ArrayList<GroupInfoEntity> list = new ArrayList<GroupInfoEntity>();
	private SalonAdapter adapter;
	private int pageNum = 1;
	private String id = "1"; // 商户id
	GroupInfoEntity cacheGroupInfoEntity;
	private SmartFoxClient mSmartFoxClient;
	private ChatUserHelper chatUserHelper;
	private AppData mAppData;
	private String classid = "";
	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_COLLECT_GROUP_NOT)) {
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(ServerCenterServerSalonActivity.this,R.string.groupNewFail);
				} else {
					SalonHttpUtil.requestUnfollowToSalonResult(ServerCenterServerSalonActivity.this,cacheGroupInfoEntity, mAppData, chatUserHelper);
					adapter.notifyDataSetChanged();
				}
			} else if (action.equals(MessagePushService.ACTION_COLLECT_GROUP)) {
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(ServerCenterServerSalonActivity.this,R.string.groupNewFail);
				} else {
					SalonHttpUtil.requestAttentionToSalonResult(ServerCenterServerSalonActivity.this,cacheGroupInfoEntity, mAppData, chatUserHelper);
					adapter.notifyDataSetChanged();
				}
			}else if (action.equals(MessagePushService.ACTION_MESSAGE)) {
				if (intent.hasExtra("senderId")) {
					adapter.notifyDataSetChanged();
					}}
		}
	};

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.server_center_server_salon_layout);
		mSmartFoxClient = SmartFoxClient.getSmartFoxClient();
		mAppData = HTalkApplication.getAppData();
		chatUserHelper = ChatUserHelper.getInstance();
//		findViewById(R.id.bic).setBackgroundResource(getIntent().getIntExtra("PICID", R.drawable.bj_doctorhouse));
		initView();
		id = getIntent().getStringExtra("id");
		initData(classid);
	}

	// 注册广播
	@Override
	public void onStart() {
		if (!SmartControlClient.getControlClient().isConnected()) {
			mSmartFoxClient.doConnecion();
		}
		IntentFilter filter = new IntentFilter(MessagePushService.ACTION_GROUPLIST);
		// 取消关注的过滤器
		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP_NOT);
		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP);
		filter.addAction(MessagePushService.ACTION_MESSAGE);
		registerReceiver(receiver, filter);
		super.onStart();
	}

	private void initData(String classid) {
		HttpRestClient.doHttpSalonSavant2(SmartFoxClient.getLoginUserId(), id,String.valueOf(pageNum), "10", classid,
				new ObjectHttpResponseHandler(this) {


					@Override
					public Object onParseResponse(String cotent) {
						return SalonHttpUtil.jsonAnalysisSalonEntity(ServerCenterServerSalonActivity.this, cotent);
					}

					public void onSuccess(int statusCode, Object response) {
						list.addAll((Collection<? extends GroupInfoEntity>) response);
						if (list.size() == 0)
							ToastUtil.showToastPanl("暂无内容...");
						adapter.notifyDataSetChanged();
						pageNum++;
					};

					public void onFinish() {
						super.onFinish();
						mPullToRefreshListView.onRefreshComplete();
					};
				});
	}

	private void initView() {
		initTitle();
		titleTextV.setText(getIntent().getStringExtra("title"));
		titleLeftBtn.setOnClickListener(this);
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleRightBtn2.setOnClickListener(this);
		titleRightBtn2.setBackgroundResource(R.drawable.icon_search_press);
		adapter = new SalonAdapter(ServerCenterServerSalonActivity.this, list);
		mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.hall);
		mListView = mPullToRefreshListView.getRefreshableView();
		mListView.setAdapter(adapter);
		mListView.setOnItemClickListener(this);
		adapter.setonClickSalonHeadListener(this);
		adapter.setonClickSalonAttentionListener(this);
		mPullToRefreshListView.setOnRefreshListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.title_right2:
			Intent intent = new Intent(this,ServerCenterSeachDoctorActivity.class);
			intent.putExtra("id", id);// 商户id
			intent.putExtra("type", "Salon");
			startActivityForResult(intent, 5000);
			break;
		}
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent data) {
		super.onActivityResult(arg0, arg1, data);
		switch (arg0) {
		case 5000:
			if(data!=null&&data.hasExtra("classID")){
				classid = data.getStringExtra("classID");
				pageNum = 1;
				list.clear();
				initData(classid);	
			}
			break;
		case 1000:
			if (data != null && data.hasExtra("SalonNewActivity")) {
				// 其他就是创建新沙龙返回更新我的沙龙里面的数据
				return;
			} else if (data != null && data.hasExtra("mSalonInformationEntity")) {
				// 从沙龙信息加关注和取消关注里面返回
				if ((Integer) data.getExtras().get("position") != -1) {
					GroupInfoEntity entity = (GroupInfoEntity) data.getExtras().get("mSalonInformationEntity");
					list.set((Integer) data.getExtras().get("position"), entity);
					adapter.notifyDataSetChanged();
				}
				return;
			}
			break;
		}
	}

	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		initData(classid);
	}

	// 沙龙头像的点击事件
	@Override
	public void onSalonHeadClick(View v, GroupInfoEntity entity, int position) {
		if (entity.getCreateCustomerID()
				.equals(SmartFoxClient.getLoginUserId())) {
			Intent intent = new Intent();
			intent.setClass(ServerCenterServerSalonActivity.this,SalonReadSelf.class);
			intent.putExtra("id", entity.getId());
			startActivity(intent);
		} else {
			Intent intent = new Intent();
			intent.setClass(ServerCenterServerSalonActivity.this,SalonInformationActivity.class);
			intent.putExtra("id", entity.getId());
			intent.putExtra("position", position);
			startActivityForResult(intent, 1000);
		}
	}

	@Override
	public void onStop() {
		ServerCenterServerSalonActivity.this.unregisterReceiver(receiver);
		super.onStop();
	}

	@Override
	public void onSalonAttentionClick(View v, GroupInfoEntity mSalonName,
			int positon) {
		cacheGroupInfoEntity = SalonHttpUtil.requestAttOrUnfollowToSalon(
				ServerCenterServerSalonActivity.this, mSalonName);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		SalonHttpUtil.onItemClick(getApplicationContext(), this,
				getSupportFragmentManager(), list.get(position - 1), false);
	}

	@Override
	public void onTicketHandler(String state, GroupInfoEntity entity) {
		switch (Integer.valueOf(state)) {
		case 0:
			// 多美币不足
//			ToastUtil.showShort(getApplicationContext(), "多美币不足");
			break;
		case 1:
			if ("0".equals(state)) {
//				ToastUtil.showShort(getApplicationContext(), "多美币不足");
			} else if ("-1".equals(state)) {
				ToastUtil.showShort(getApplicationContext(), "服务器出错");
			} else {
				Intent intent1 = new Intent();
				intent1.putExtra(ChatActivity.KEY_PARAME, entity);
				intent1.setClass(getApplicationContext(), ChatActivity.class);
				startActivity(intent1);
				mAppData.updateLatelyGroup(entity);
				mAppData.updateCacheInfomation(entity);
				CollectUtils.updateGroupRecent(chatUserHelper, entity,SmartFoxClient.getLoginUserId());
			}
			break;
		}
	}

}
